package com.atguigu.system.service.impl;

import com.atguigu.model.system.SysUser;
import com.atguigu.springsecurity.coutom.LoginUser;
import com.atguigu.system.exception.GuiguException;
import com.atguigu.system.mapper.SysMenuMapper;
import com.atguigu.system.service.SysUserService;
import io.swagger.annotations.Api;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.*;

import javax.annotation.Resource;


@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Resource
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        // 调用方法得到
        SysUser user = sysUserService.getUserInfoByUserName(userName);

        // 如果没有查询到用户就抛出异常
        if(user == null) {
            // 因为有一个ExceptionTransaltion的全局异常处理器
            // 过程中异常的信息就可以被捕获
            throw new GuiguException(201 ,"用户名或者密码错误");
        }

        // TODO 查询对应的权限信息
        // permissions就是这个权限的
        List<String> perms = sysMenuMapper.getUerMenuPermsList(user.getId());

        LoginUser loginUser = new LoginUser(user, perms);

        return loginUser;

    }
}
